package com.change.study.data.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.change.study.data.core.BaseDaoImpl;
import com.change.study.data.core.Finder;
import com.change.study.data.core.Pagination;
import com.change.study.data.dao.UserLimitsDao;
import com.change.study.data.entity.User;
import com.change.study.data.entity.UserLimits;
import com.change.study.data.entity.UserPoints;

@Repository
public class UserLimitsDaoImpl extends BaseDaoImpl<UserLimits, Long> implements
		UserLimitsDao {
	public Pagination getPage(int pageNo, int pageSize) {
		Criteria crit = createCriteria();
		Pagination page = findByCriteria(crit, pageNo, pageSize);
		return page;
	}

	public UserLimits findById(Long id) {
		UserLimits entity = get(id);
		return entity;
	}

	public UserLimits save(UserLimits bean) {
		getSession().save(bean);
		return bean;
	}

	public UserLimits deleteById(Long id) {
		UserLimits entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@Override
	protected Class<UserLimits> getEntityClass() {
		return UserLimits.class;
	}

	@Autowired
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public UserLimits findByUserId(Long id, String action) {
		UserLimits result = null;
		Finder finder = Finder
				.create("from UserLimits u where u.user.id=:userid");
		finder.setParam("userid", id);
		finder.append(" and u.action = :action");
		finder.setParam("action", action);
		List<UserLimits> list = find(finder);
		if (list != null && list.size() > 0) {
			result = list.get(0);
		} else {
			result = new UserLimits();
			User user = new User();
			user.setId(id);
			result.setAction(action);
			result.setCount(1);
			result.setUser(user);
			save(result);
		}
		int period = result.getPeriod();
		int p = (int) (System.currentTimeMillis() / (3600 * 1000));
		if (p == period) {
			result.setCount(result.getCount() + 1);
		} else {
			result.setCount(1);
			period = p;
		}
		result.setPeriod(period);
		return result;
	}
}